package com.snow.controller.admin;

import com.github.pagehelper.PageInfo;
import com.snow.constant.Types;
import com.snow.constant.Webconst;
import com.snow.controller.BaseController;
import com.snow.pojo.dto.StatisticsDto;
import com.snow.pojo.model.*;
import com.snow.service.log.LogService;
import com.snow.service.meta.MetaService;
import com.snow.service.options.OptionsService;
import com.snow.service.site.SiteService;
import com.snow.service.user.UserService;
import com.snow.utils.AdminCommons;
import com.snow.utils.Commons;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.Soundbank;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @author: snow
 * @Date: 2020-01-11
 **/
@Api("后台index页")
@Controller
@RequestMapping("/admin")
public class AdminIndexController extends BaseController {
    private static final Logger logger = Logger.getLogger(AdminIndexController.class);
    @Autowired
    private SiteService siteService;
    @Autowired
    private LogService logService;
    @Autowired
    private UserService userService;
    @Autowired
    private Commons commons;
    @Autowired
    private AdminCommons adminCommons;
    @Autowired
    private OptionsService optionsService;
    @Autowired
    private MetaService metaService;


    @GetMapping({"", "/index"})
    public String index(Model model){
        logger.info("Enter admin index controller");
        model.addAttribute("commons",commons);
        model.addAttribute("adminCommons",adminCommons);
        model.addAttribute("options", optionsService.getOptionsByName("site_record"));
        List<ContentDomain> newArticles = siteService.getNewArticles(5);
        List<CommentDomain> comments = siteService.getComments(5);
        StatisticsDto statics = siteService.getStatics();
        PageInfo<LogDomain> logs = logService.getLogs(1, 5);
        List<LogDomain> list = logs.getList();
        logger.info("NewArticles is " + newArticles.size());
        model.addAttribute("comments",comments);
        model.addAttribute("articles",newArticles);
        model.addAttribute("statistics",statics);
        model.addAttribute("logs",list);
        this.userInfo(model);
        return "admin/index";
    }
    @GetMapping("/login")
    public String toLogin(Model model){
        model.addAttribute("commons",commons);
        return "admin/login";
    }

    @PostMapping("/login")
    public String checkLogin(String username, String password, Model model,
                             HttpServletRequest request, boolean rememberMe,
                             RedirectAttributes redirectAttributes){

        //获取当前用户
        String uri = request.getRequestURI();
        logger.info("URI===>" + uri);
        logger.info("用户访问的ip====>" + request.getRemoteAddr());
        logger.info("用户代理====>" + request.getHeader("user-agent"));
        Subject subject = SecurityUtils.getSubject();
        UserDomain user = userService.getUserByUsername(username);
        Session session = subject.getSession();
        session.setAttribute(Webconst.LOGIN_SESSION_KEY,user);
        //封装登录信息，令牌
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(rememberMe);
        try {
            model.addAttribute("commons",commons);
            logger.info(rememberMe);
            subject.login(token);
            initConfig();
            logger.info("return index");
            Integer uid = userService.getUserByUsername(username).getUid();
            logService.addLog("登录后台",username,session.getHost(),uid);
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名不存在");
            return "admin/login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg", "密码错误");
            return "admin/login";
        }
        List list = subject.getPrincipals().asList();
        HashMap map = (HashMap)list.get(0);
        UserDomain loginUser = (UserDomain) map.get("user");
        System.out.println("debug===================>loginUser UId = " + loginUser.getUid());
        //将登陆的用户缓存起来
        this.cacheMap.set("loginUser",loginUser);
        return "redirect:/admin/index";
    }
    @RequestMapping("/logout")
    public String logout(Model model){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("commons",commons);
        return "admin/login";
    }
    private void initConfig(){
        if(Webconst.initConfig.isEmpty()){
            HashMap<String, String> map = new HashMap<>();
            List<OptionsDomain> options = optionsService.getAllOptions();
            options.forEach(option->{
                map.put(option.getName(),option.getName());
            });
            Webconst.initConfig = map;
        }
    }

}
